const { ObjectId } = require('mongodb')
const linkModel = require('../models/link')

const updateLink = async (req, res) => {
  const { id, name, link, sort } = req.body

  // 转更新
  if (id) {
    const filter = { _id: id }
    const update = { $set: { name, link, sort } }
    await linkModel.updateOne(filter, update)
    return res.send({
      msg: 'ok',
    })
  }

  const result = await linkModel.create({ name, link, sort })

  res.send({
    msg: 'ok',
    data: result,
  })
}

const linkList = async (req, res) => {
  const result = await linkModel.find()
  res.send({
    code: 200,
    data: result,
  })
}

const delLink = async (req, res) => {
  const { id } = req.query
  if (!id) {
    return res.send({
      msg: 'not fount',
      code: 400,
    })
  }
  const result = await linkModel.deleteOne({ _id: id })
  return res.send({
    code: 200,
    msg: 'ok',
    data: result,
  })
}

module.exports = {
  linkList,
  updateLink,
  delLink,
}
